package pay.serviceImpl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pay.common.CardStatusCode;
import pay.common.ChangeCardResultCode;
import pay.common.ConstantRoute;
import pay.common.HqlFilter;
import pay.entity.Payment;
import pay.entity.SysUser;
import pay.portal.web.message.FM;
import pay.portal.web.message.PaymentMsg;
import pay.service.IMessageService;
import pay.service.IPayment;
import pay.service.sys.ISysUser;
import pay.serviceImpl.dao.base.impl.BaseServiceImpl;
import pay.utils.*;

@Service
public class PaymentImpl extends BaseServiceImpl<Payment> implements IPayment {

	private Logger logger = LoggerFactory.getLogger(PaymentImpl.class);

	@Autowired
	private ISysUser userService;

	@Autowired
	private IMessageService messageService;

	@Override
	public Payment findById(long id) {
		return getById(id);
	}

	@Override
	public Long add(Payment model) {
		Long id = null;
		if (model != null && model.getPaymentNo() != null) {
			id = LongId.get();
			model.setId(id);
			model.setCts(System.currentTimeMillis());
			if (StringHelper.isNotEmpty(model.getAccountName())) {
				model.setAccountName(model.getAccountName().trim());
			} else if (model.getUserId() != null) {
				SysUser user = userService.findById(model.getUserId());
				if (user != null && StringHelper.isNotEmpty(user.getRealName())) {
					model.setAccountName(user.getRealName());
				}

			}
			if (StringHelper.isNotEmpty(model.getIdentityNo())) {
				model.setIdentityNo(model.getIdentityNo().toUpperCase());
			}
			model.setPaymentNo(model.getPaymentNo().trim());
			super.save(model);
			logger.info("add result true new Id = " + id);

			String msg = String.format("恭喜您，绑卡成功！请在我的-我的银行卡中进行查看");
			this.messageService.sendMsg(String.valueOf(model.getUserId()), msg, "绑卡成功", ConstantPush.WITHDRAW, MsgTypeConstants.BIND_CARD);
		}		
		try {
			logger.info("添加到redis中");
			
			RedisCilent.listSet(CacheConstants.FINALCIAL_PUSH,
					JsonUtils.toJson(getPaymentMsg(model)));
		} catch (Exception e) {
			logger.error("add payment error" ,e);
		}
		
		return id;
	}

	private PaymentMsg getPaymentMsg(Payment payment) {
		PaymentMsg paymentMsg = new PaymentMsg();
		paymentMsg.setUserId(payment.getUserId());
		paymentMsg.setAccountName(payment.getAccountName());
		return paymentMsg;
	}
	@Override
	public Payment getByUserId(Long userId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addEQFilter("cardStatus", 1);
		hqlFilter.addSort("cts");
		return getByFilter(hqlFilter);
	}

	@Override
	public Payment getByPaymentNo(String paymentNo) {
		Payment payment = null;
		if (StringHelper.isNotEmpty(paymentNo)) {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("paymentNo", paymentNo);
			payment = getByFilter(hqlFilter);
		}
		return payment;
	}

	@Override
	public Boolean isSame(Payment a, Payment b) {
		Boolean result = false;

		if (a != null && b != null && a.getUserId().equals(b.getUserId())
				&& a.getPaymentNo().equals(b.getPaymentNo())
				&& a.getPhone().equals(b.getPhone())) {
			result = true;
		}
		logger.info("isSame result = " + result);
		return result;
	}

	@Override
	public Boolean existById(Long id) {

		Payment payment = getById(id);

		return payment != null;
	}

	/**
	 * 检查支付方式是否相同
	 * 
	 * @param pay01
	 * @param pay02
	 * @return
	 */
	@Override
	public Boolean checkSamePayment(Payment pay01, Payment pay02) {
		Boolean result = false;
		// 如果订单的支付信息id不为空
		if (pay01 == null || pay02 == null) {
			return false;
		}

		if (checkFullMsg(pay01) && checkFullMsg(pay02)) {
			if (pay01.getAccountName().equalsIgnoreCase(pay02.getAccountName())
					&& pay01.getPaymentNo().equalsIgnoreCase(
							pay02.getPaymentNo())
					&& pay01.getIdentityNo().equalsIgnoreCase(
							pay02.getIdentityNo())
					&& pay01.getPhone().equalsIgnoreCase(pay02.getPhone())) {

				result = true;
			} else {
				result = false;
			}
		} else {
			result = false;
		}
		logger.info("checkSamePayment result = " + result);
		return result;
	}

	@Override
	public Boolean checkFullMsg(Payment pay) {

		Boolean result = true;

		if (pay == null) {
			return false;
		}

		if (StringHelper.isEmpty(pay.getAccountName())
				|| StringHelper.isEmpty(pay.getPhone())
				|| StringHelper.isEmpty(pay.getIdentityNo())
				|| StringHelper.isEmpty(pay.getPaymentNo())) {

			logger.info("checkFullMsg failed : accountName = "
					+ pay.getAccountName() + "  phone = " + pay.getPhone()
					+ "  identityNo = " + pay.getIdentityNo()
					+ "  paymentNo = " + pay.getPaymentNo());
			result = false;
		}
		return result;
	}

	@Override
	public Long add(Payment u, Integer companyId) {
		u.setSupportCompany(getCompanyInfo(companyId));
		Long id = this.add(u);
		return id;
	}

	private String getCompanyInfo(Integer companyId) {
		return "-" + companyId + "-";
	}

	@Override
	public void setAddCardCompany(Integer company, Payment payment) {
		String surpportCompany = payment.getSupportCompany();
		if (StringHelper.isEmpty(surpportCompany)) {
			surpportCompany = CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD;
		}
		String[] companies = surpportCompany.split(",");
		switch (company) {
		case ConstantRoute.COMPANY_HUAKANG:
			surpportCompany = ConstantRoute.COMPANY_HUAKANG + ","
					+ companies[1] + "," + companies[2];
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			surpportCompany = companies[0] + ","
					+ ConstantRoute.COMPANY_HUOCHAI + "," + companies[2];
			break;
		case ConstantRoute.COMPANY_YINGMI:
			surpportCompany = companies[0] + "," + companies[1] + ","
					+ ConstantRoute.COMPANY_YINGMI;
			break;
		default:
			break;
		}

		payment.setSupportCompany(surpportCompany);
		logger.info("当前卡号设置绑卡公司为：surpportCompany={}", surpportCompany);
	}

	@Override
	public String getCardCompany(Integer company, Payment payment) {
		String resultCompany = "";
		String supportCompanys = payment.getSupportCompany();// 1，3，4代表三家公司富友、火柴、盈米
		if (StringHelper.isNotEmpty(supportCompanys)) {
			String[] companys = supportCompanys.split(",");
			switch (company) {
			case ConstantRoute.COMPANY_HUAKANG:
				resultCompany = companys[0];
				break;
			case ConstantRoute.COMPANY_HUOCHAI:
				resultCompany = companys[1];
				break;
			case ConstantRoute.COMPANY_YINGMI:
				resultCompany = companys[2];
				break;
			default:
				break;
			}
		}
		return resultCompany;
	}

	@Override
	public void changeSupportCardStatus(Integer company, Payment payment,
			Integer cardStatus) {
		String surpportCompany = payment.getSupportCompany();
		if (StringHelper.isEmpty(surpportCompany)) {
			surpportCompany = CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD;
		}
		String[] companies = surpportCompany.split(",");
		switch (company) {
		case ConstantRoute.COMPANY_HUAKANG:
			surpportCompany = cardStatus + "," + companies[1] + ","
					+ companies[2];
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			surpportCompany = companies[0] + "," + cardStatus + ","
					+ companies[2];
			break;
		case ConstantRoute.COMPANY_YINGMI:
			surpportCompany = companies[0] + "," + companies[1] + ","
					+ cardStatus;
			break;
		default:
			break;
		}

		payment.setSupportCompany(surpportCompany);
		logger.info("当前卡号更改绑卡渠道为：surpportCompany={}", surpportCompany);
	}

	@Override
	public Payment addOrUpdatePayment(String capAcntNo, String cust_nm,
			String certif_id, String mobile_no, SysUser user) {
		Payment newPayment=null;
		HqlFilter filter = new HqlFilter();
		filter.addEQFilter("paymentNo", capAcntNo);
		filter.addEQFilter("cardStatus", CardStatusCode.PAYMENT_DISPLAY_SHOW);//只有一张卡能换
		filter.addSql(" and identityNo in('"+user.getIdentity()+"','"+user.getIdentity().toUpperCase()+"')");
		List<Payment> existPaymentList = this.findByFilter(filter);
		if (existPaymentList.size() > 0) {
			logger.info("已存在卡号，即将更新paymentId={}", existPaymentList.get(0)
					.getId());
			newPayment=updateNewPaymentExist(existPaymentList,// 更新已存在的而在富友添加的卡。
					certif_id, cust_nm);
		} else {
			logger.info("将添加绑卡记录userId={}", user.getId());
			newPayment=addNewCard(cust_nm, certif_id, capAcntNo,// 添加新卡
					mobile_no, user);

		}
		return newPayment;
	}

	@Override
	public Long updateExistPayment(Payment willChangePayment) {// 更新被替换的卡
		String payemntMchnt_txn_ssn = willChangePayment.getMchnt_txn_ssn();// 获取换卡请求流水
		String paymentIdStr = payemntMchnt_txn_ssn.substring(6);
		Long paymentId = Long.parseLong(paymentIdStr);
		Payment oldPayment = this.findById(paymentId);

        return updateOldPayment(oldPayment);
    }

    @Override
    public Long updateOldPayment(Payment oldPayment) {
        // 换卡，原卡被替换，新卡新增加

        this.changeSupportCardStatus(ConstantRoute.COMPANY_HUAKANG, oldPayment, CardStatusCode.FY_CARD_WASCHANGED);
        String ym = this.getCardCompany(ConstantRoute.COMPANY_YINGMI, oldPayment);
        String hc = this.getCardCompany(ConstantRoute.COMPANY_HUOCHAI, oldPayment);

        boolean isYM = ("" + ConstantRoute.COMPANY_YINGMI).equals(ym);
        boolean isHC = ("" + ConstantRoute.COMPANY_HUOCHAI).equals(hc);
        boolean isOnlyFY = !(isYM || isHC);

        if (isOnlyFY) {
            oldPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_HIDE);
            oldPayment.setChangeCardResult(ChangeCardResultCode.CHANGED);
        } else {
            oldPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
        }

        oldPayment.setMchnt_txn_ssn(null);
        this.update(oldPayment);
        return oldPayment.getId();
    }

    @Override
	public Payment updateNewPaymentExist(List<Payment> currentPaymentList,// 更新已存在的而在富友添加的卡。
			String certif_id, String cust_nm) {
		Payment existPayment = currentPaymentList.get(0);
		this.setAddCardCompany(ConstantRoute.COMPANY_HUAKANG, existPayment);
		if (StringHelper.isEmpty(existPayment.getIdentityNo())) {
			existPayment.setIdentityNo(certif_id);
		}
		if (StringHelper.isEmpty(existPayment.getAccountName())) {
			existPayment.setAccountName(cust_nm);
		}
		existPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
		existPayment.setCts(System.currentTimeMillis());
		this.update(existPayment);
		return existPayment;
	}

	@Override
	public Payment addNewCard(String cust_nm, String certif_id, String capAcntNo,// 添加新卡
			String mobile_no, SysUser user) {
		Payment newPayment = new Payment();
		newPayment.setAccountName(cust_nm);
		newPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
		newPayment.setCts(System.currentTimeMillis());
		newPayment.setId(LongId.get());
		newPayment.setIdentityNo(certif_id);
		newPayment.setPaymentNo(capAcntNo);
		newPayment.setPhone(mobile_no);
		newPayment.setUserId(user.getId());
		newPayment.setUserRegistPhone(user.getName());
		newPayment.setSupportCompany(ConstantRoute.COMPANY_HUAKANG + ","
				+ CardStatusCode.NEVER_BIND_CARD + ","
				+ CardStatusCode.NEVER_BIND_CARD);

		FM fm = FYApiUtil.getBankCardInfo(capAcntNo);
		if (fm != null) {
			if (StringHelper.isNotEmpty(fm.getCnm())) {
				newPayment.setCardType(fm.getCtp());// 卡类型
				newPayment.setBankName(fm.getCnm());// 银行名称
				newPayment.setInsCard(fm.getInscd());// 银行机构号
			}
		}
		this.add(newPayment);
		return newPayment;
	}

}
